﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Threading;
using System.Diagnostics;
using System.Runtime.Serialization.Json;
using System.Net;
using YeaTrip.Common;

namespace YeaTrip.Comet
{
    public class CometAsyncHandler : IHttpAsyncHandler
    {
        #region IHttpAsyncHandler Members

        /// <summary>
        /// 请求入口
        /// </summary>
        /// <param name="context"></param>
        /// <param name="cb"></param>
        /// <param name="extraData"></param>
        /// <returns></returns>
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            // check clientid first (here use agentid)
            if (string.IsNullOrWhiteSpace(context.Request["CustID"]))
            {
                //context.Response.StatusCode = (int) HttpStatusCode.Redirect;
                context.Response.StatusCode = 500;
                context.Response.Write("无效请求，CustID无效");
                context.Response.End();
                return null;
            }
            
            //  get the result here
            CometAsyncResult result = new CometAsyncResult(context, cb, extraData);

            result.BeginWaitRequest();

            //  ok, return it
            return result;
        }

        public void EndProcessRequest(IAsyncResult result)
        {
            CometAsyncResult cometAsyncResult = result as CometAsyncResult;

            if (cometAsyncResult != null && cometAsyncResult.ResponseObject != null)
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(cometAsyncResult.ResponseObject.GetType());
                serializer.WriteObject(cometAsyncResult.HttpContext.Response.OutputStream, cometAsyncResult.ResponseObject);
            }

            try
            {
                // 防止客户端关闭引发异常
                cometAsyncResult.HttpContext.Response.End();
            }
            catch { }
        }

        #endregion

        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            throw new InvalidOperationException("ASP.NET Should never use this property");
        }

        #endregion
    }
}
